<template>
	<view v-if="isCanUse">
		<view>
			<view class='header'>
				<image src='/static/icon/wx.png'></image>
			</view>
			<view class='content'>
				<view>申请获取以下权限</view>
				<text>获得你的公开信息(昵称，头像、地区等)</text>
			</view>

			<button class='bottom' type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">
				授权登录
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgurl: '/pages/views/engineer/test/wx.png',
				SessionKey: '',
				OpenId: '',
				nickName: null,
				avatarUrl: null,
				isCanUse:  uni.getStorageSync('isCanUse')?false:true //默认为true
			};
		},
		methods: {

			//第一授权获取用户信息===》按钮触发
			wxGetUserInfo() {
				let _this = this;
				uni.getUserInfo({
					provider: 'weixin',
					success: function(infoRes) {
						let nickName = infoRes.userInfo.nickName; //昵称
						let avatarUrl = infoRes.userInfo.avatarUrl; //头像
						let js_code = infoRes.code;
						let formdata = {
							nickName: nickName,
							avatarUrl: avatarUrl,
							js_code: js_code
						}
						try {
							uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
							_this.isCanUse = uni.getStorageSync('isCanUse')
							// _this.updateUserInfo();
						} catch (e) {}
						console.log(formdata)
					},
					fail(res) {}
				});
			},
			login() {
				var self = this;
				uni.showLoading({
					mask: true,
					title: '正在登录···',
					complete: () => {}
				});

				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						//js_code可以给后台获取unionID或openID作为用户标识
						let js_code = loginRes.code; 
						if (!self.isCanUse) {
							// 获取用户信息
							uni.getUserInfo({
								provider: 'weixin',
								success: function(infoRes) {
									//infoRes里面有用户信息需要的话可以取一下
									let username = infoRes.userInfo.nickName; //用户名
									let gender = infoRes.userInfo.gender; //用户性别
									let formdata = {
										code: js_code,
										username: username,
										sex: gender
									};
									console.log(formdata)
									//login是接口地址，看下面PHP代码
									// self.$go.post("/login",formdata).then(res=>{//这是我封装的请求方法
									// 	if(res.code==200){
									// 		//登录成功
									// 	}
									// })
									uni.hideLoading()
								},
								fail: function(res) {}
							})
						}
					},
					fail: function(res) {}
				})

				uni.hideLoading()
			}

		},
		onLoad() { //默认加载
			this.login();
		}
	}
</script>

<style>
	.header {
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 300rpx;
		line-height: 450rpx;
	}

	.header image {
		width: 200rpx;
		height: 200rpx;
	}

	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40rpx;
	}

	.bottom {
		border-radius: 80rpx;
		margin: 70rpx 50rpx;
		font-size: 35rpx;
	}
</style>
